<script setup lang="ts">
import { onMounted, ref, defineEmits } from 'vue'
import { searchByKeyword, searchProducts } from '@/api/search'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const searchContainer = ref<HTMLElement | null>(null)
const props = defineProps({
  showRank: {
    type: Boolean,
    default: true,
  },
  searchConds: {
    type: Object
  }
})

const emits = defineEmits(['searchData'])


const params = ref({
  keyword: '',
  saleNum: true,
  startPrice: null,
  endPrice: null,
  page: 1,
  pageSize: 20,
})
const history = ref(JSON.parse(localStorage.getItem('history') || '[]'))
const isFocus = ref(false)

const matchList = ref<any[]>([])

const showPanel = () => {
  isFocus.value = true
}

const handlechange = (e: any) => {
  let timer = setInterval(async () => {
    clearInterval(timer)
    console.log('timer')
    if (!e.target.value) {
      matchList.value = []
      return
    }
    params.value.keyword = e.target.value
    const { data: res } = await searchByKeyword(params.value.keyword)
    matchList.value = res.data
  }, 1000)
}

const goDetail = (item: any) => {
  let pattern = /<[^>]+>/g

  router.replace({
    path: `/product`,
    query: {
      title: item.replace(pattern, '')
    }
  })
}


const handleHistory = (item: string) => {
  params.value.keyword = item
  router.push({
    path: '/search',
    query: {
      keyword: params.value.keyword,
    },
  })
}

const defaultSearch = () => {
  console.log('search conditions', params.value)
  if (!history.value.includes(params.value.keyword) && params.value.keyword) {
    history.value.push(params.value.keyword)
    localStorage.setItem('history', JSON.stringify(history.value))
  }
  router.push({
    path: '/search',
    query: {
      keyword: params.value.keyword,
    },
  })
  initSearch()
}

const search = async () => {
  defaultSearch()
}

const clearHistory = () => {
  localStorage.removeItem('history')
  history.value.length = 0
}

const closePanel = (e: any) => {
  !searchContainer.value?.contains(e.target) && (isFocus.value = false)
}

const initSearch = async () => {
  if(route.query.keyword) {
    params.value = props.searchConds ? props.searchConds : { keyword: route.query.keyword }
    console.log('组件 search conditions', params.value)
    const { data: res } = await searchProducts(params.value)
    emits('searchData', res.data)
  }
}


onMounted(() => {
  window.addEventListener('click', closePanel)
  initSearch()
})
</script>

<template>
  <div class="search-container flex-row">
    <div class="left-entry">
      <div class="logo-box" :class="showRank ? '' : 'simple'">
        <img src="/src/assets/logo.png" alt="" />
      </div>
    </div>
    <div class="center-search-container" ref="searchContainer">
      <div class="search-bar">
        <div :class="['search-box', isFocus ? 'focus' : '']">
          <div class="search-content">
            <input
              type="text"
              placeholder="请输入搜索内容"
              @focus="showPanel"
              @input="handlechange"
              v-model="params.keyword"
            />
          </div>
          <div class="search-btn" @click="search">
            <button>搜索</button>
          </div>
        </div>
        <div :class="['search-panel', isFocus ? 'show' : '']">
          <div class="matchList">
            <div
              class="match-item"
              v-for="(item, index) in matchList"
              :key="index"
              v-html="item"
              @click="goDetail(item)"
            ></div>
          </div>
          <div class="history" v-if="history.length > 0">
            <div class="header search-history">
              搜索历史
              <div class="clear-history" @click="clearHistory">
                <span>清空历史</span>
              </div>
            </div>
            <div class="history-list">
              <div
                class="history-item"
                v-for="(item, index) in history"
                :key="index"
                @click="handleHistory(item)"
              >
                {{ item }}
              </div>
            </div>
          </div>
          <div class="match">
            <div class="header">搜索推荐</div>
          </div>
        </div>
      </div>
      <div class="recommend-box" v-if="props.showRank">
        <span class="strong">大额神券</span>
        <span>iPhone惊喜券</span>
        <span>买一送一</span>
        <span>运功爆款</span>
        <span>3c数码优惠</span>
        <span>女装</span>
        <span>货架</span>
        <span>空调</span>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.search-container {
  display: flex;
  width: 100%;
  align-items: center;
  .left-entry {
    width: 20%;
  }
  .logo-box {
    max-width: 100px;
    height: 100px;
    margin: 0 auto;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .center-search-container {
    width: 60%;
  }
  .search-bar {
    position: relative;
    box-sizing: border-box;
    border-radius: 8px 8px 0 0;
  }
  .search-box {
    display: flex;
    padding: 0 80px 0 0px;
    border-radius: 8px;
    box-sizing: border-box;
    border: 2px solid #ff5000;
    &.focus {
      border-radius: 8px 8px 0 0;
      border-bottom: none;
    }
  }
  .search-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    padding: 0 8px;
    width: 100%;
    height: 32px;
    border: 2px solid transparent;
    border-radius: 6px;
    input {
      flex: 1;
      overflow: hidden;
      padding-right: 8px;
      border: none;
      background-color: transparent;
      box-shadow: none;
      color: #666;
      font-size: 14px;
      line-height: 32px;
      outline: none;
    }
  }
  .search-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    padding: 0;
    width: 76px;
    height: 32px;
    border: none;
    border-radius: 8px;
    color: #000;
    line-height: 32px;
    button {
      cursor: pointer;
      outline: none;
      width: 80px;
      height: 100%;
      border: none;
      color: #fff;
      border-radius: 8px;
      background-color: #ff5000;
    }
  }
}

.search-panel {
  z-index: 300;
  display: none;
  position: absolute;
  left: 0;
  top: 100%;
  box-sizing: border-box;
  width: 100%;
  max-height: 612px;
  background: #fff;
  border: 2px solid #ff5000;
  border-top: none;
  border-radius: 0 0 8px 8px;
  padding: 13px 10px 16px 10px;
  .match-item {
    margin-bottom: 10px;
    /deep/ span {
      color: #ff5000 !important;
    }
    &:last-child {
      margin-bottom: 20px;
    }
  }
  -webkit-font-smoothing: antialiased;
  &.show {
    display: block;
  }
  .history {
    margin-bottom: 10px;
  }
}

.search-history {
  display: flex;
  height: 30px;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .clear-history {
    cursor: pointer;
    color: #999;
    font-size: 12px;
    line-height: 12px;
  }
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  .history-item {
    margin-right: 10px;
    margin-bottom: 10px;
    padding: 0 10px;
    height: 24px;
    line-height: 24px;
    border: 1px solid #e5e5e5;
    border-radius: 12px;
    color: #333;
    font-size: 12px;
    cursor: pointer;
  }
}

.recommend-box {
  margin-top: 10px;
  text-align: center;
  span {
    margin-right: 8px;
    font-size: @small-font-size;
  }
  .strong {
    color: @primary-color;
  }
}

@media screen and (max-width: 890px) {
  .logo-box {
    display: none;
  }
  .left-entry {
    display: none;
  }
  .center-search-container {
    width: 100% !important;
  }
  .recommend-box {
    margin-bottom: 10px;
  }
}

@media screen and (max-width: 480px) {
  .logo-box {
    display: none;
  }
  .recommend-box {
    display: none;
  }
}
</style>
